package mp

import (
	"context"
	"errors"
	"strings"

	"ruikc.com/server/api/internal/db"
	"ruikc.com/server/api/internal/svc"
	"ruikc.com/server/api/internal/types"
	"ruikc.com/server/models"
	xb "xorm.io/builder"

	"github.com/jinzhu/copier"
	"github.com/zeromicro/go-zero/core/logx"
)

type CourseSaveLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewCourseSaveLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CourseSaveLogic {
	return &CourseSaveLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CourseSaveLogic) CourseSave(req *types.CourseReq) (resp string, err error) {

	has := db.ExistData(&models.Classify{Id: req.Cid1})
	if !has {
		return "", errors.New("一级分类不存在")
	}

	has = db.ExistData(&models.Classify{Id: req.Cid2})
	if !has {
		return "", errors.New("二级分类不存在")
	}

	data := &models.Course{}
	copier.Copy(data, req)
	data.InstructorIds = strings.Join(req.InstructorIds, ",")

	if req.Id == 0 {
		db.InsertData(data)
	} else {
		db.UpdateData(data, xb.Eq{"id": req.Id})
	}

	return "操作成功", nil
}
